//
//  HomeViewController.m
//  hostView
//
//  Created by 徐宏飞 on 16/5/19.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeTableViewCell.h"
#import "XRCarouselView.h"
#import "CaroselModel.h"   //轮播图数据
#import "HomeListModel.h"  //项目列表数据

//#import "EmploymentViewController.h"
#import "CompositionViewController.h"


static NSString *HomeTableViewCell_ID = @"HomeTableViewCell";

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, XRCarouselViewDelegate,NetworkToolerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *homeTableView;
@property (nonatomic, strong) XRCarouselView *carouselView;     //轮播图
@property (nonatomic, strong) NSMutableArray *imgCaroselArrays; //轮播图数组
@property (nonatomic, strong) NSMutableArray *workerListArray;  //项目列表
@property (nonatomic, assign) NSInteger loadpage;               //页码

@property (nonatomic, strong) ZhuangxiuManager *manager;
@property (nonatomic, strong) NetworkTooler *network;
@property (nonatomic, assign) NSInteger requstType;               //
@property (nonatomic, assign) NSInteger total;               //列表总个数



@end

@implementation HomeViewController

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    // Do any additional setup after loading the view from its nib.
    
    self.imgCaroselArrays = [NSMutableArray array];
    self.workerListArray = [NSMutableArray array];
    _network  = [NetworkTooler new];
    
    
    [_homeTableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] forCellReuseIdentifier:HomeTableViewCell_ID];
    
    
    
    self.manager = [ZhuangxiuManager shareManager];
    self.loadpage = 1;
    
    self.view.hidden = YES;
//    [GiabHUD showUIBlockingIndicator];
//    [self _postCaroselData];
    
    
    __weak HomeViewController *weakself = self;
    
    _homeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        self.page = 0;
        
        [weakself updateNewData];
    }];
    
    _homeTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakself updateMoreData];
    }];
    if (!self.enableReturnButton) {
//        _homeTableView.hidden = YES;
        
    }
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GiabHUD showUIBlockingIndicator];
//    [self _postCaroselData];
    [self _postCaroselData];

    [MobClick beginLogPageView:@"Home"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"Home"];
}

#pragma mark - Data
- (void) _postCaroselData{
 
    _requstType = 2;
    
    _network.delegate = self;
    [_network parameters:nil withURL:getWorkerHomeCarosel_show  withIsPaparameters:YES];
    
    //    [FWNetTool postWithUrl:getWorkerHomeCarosel_show parameters:nil success:^(id json) {
    ////        NSLog(@"%@", json);
    //        NSMutableArray *saveArr = [NSMutableArray array];
    //
    //        NSString *code = json[@"code"];
    //        NSString *msg = json[@"msg"];
    //
    //        if (code.intValue == 0) {
    //            NSDictionary *dic = json[@"data"];
    //            NSArray *arr = dic[@"data"];
    //            for (NSMutableDictionary *dic in arr) {
    //                CaroselModel *model = [CaroselModel modelWithDictionary:dic];
    //                [self.imgCaroselArrays addObject:model];
    //                [saveArr addObject:[model.pic_url stringByAppendingString:caroselmain]];
    //            }
    //
    //            //写入本地
    //            [self _arrayWriteTofile:saveArr];
    //
    //
    //            [self.homeTableView reloadData];
    //
    //        } else {
    //            [self showAlertWithTitle:nil message:msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
    //
    //        }
    //
    //
    //    } failure:^(NSError *error) {
    //
    //
    //    }];
}

- (void) _postWorkerListDataWithPage:(NSInteger)page{
    _requstType = 1;
    
    NSString *pageStr = [NSString stringWithFormat:@"%ld", page];
    
    //    [GiabHUD showUIBlockingIndicatorWithText:@"正在加载..."];
    
    NSDictionary *parameters = @{
                                 @"page":pageStr,
                                 @"rows":[NSString stringWithFormat:@"%d",listConut]
                                 };
    _network.delegate = self;
    [_network parameters:parameters withURL:getWorkerHomeList_show  withIsPaparameters:YES];
    
    //    [FWNetTool postWithUrl:getWorkerHomeList_show parameters:parameters success:^(id json) {
    //
    ////        NSLog(@"%@", json);
    //
    //        NSDictionary *dic = [json objectForKey:@"data"];
    //        NSArray *array = [dic objectForKey:@"data"];
    //
    //        for (NSMutableDictionary *dic in array) {
    //            HomeListModel *model = [HomeListModel modelWithDictionary:dic];
    //            [self.workerListArray addObject:model];
    //        }
    //
    //
    //        [self.homeTableView reloadData];
    //        [GiabHUD hideUIBlockingIndicator];
    //    } failure:^(NSError *error) {
    //
    //        [GiabHUD hideUIBlockingIndicator];
    //
    //    }];
    
    
    
}






#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.workerListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.imgCaroselArrays.count == 0) {
        return 1;
    }
    return 150*WID;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (self.imgCaroselArrays.count != 0) {
        UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 145*WID)];
        
        NSMutableArray *array = [NSMutableArray array];
        
        
        for (CaroselModel *model in self.imgCaroselArrays) {
            [array addObject:[model.pic_url stringByAppendingString:caroselmain]];
        }
        self.carouselView = [XRCarouselView carouselViewWithImageArray:array describeArray:nil];
        //设置frame
        self.carouselView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 145*WID);
        
        self.carouselView.delegate = self;
        
        _carouselView.changeMode = ChangeModeDefault;
        
        _carouselView.time = 4;
        
        _carouselView.pagePosition = PositionBottomRight;
        
        _carouselView.pageControl.hidden = NO;
        [baseView addSubview:_carouselView];
        return baseView;
        }
    
//    if (array.count == 0) {
//        array  = [NSMutableArray arrayWithObject:FW_IMAGE(@"placeholder")];
//    }
//
    
    
    
    
    
    return nil;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeListModel *model = self.workerListArray[indexPath.row];
    
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeTableViewCell_ID];
    
    cell.model = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    HomeListModel *model = self.workerListArray[indexPath.row];
    CompositionViewController *composition = [CompositionViewController new];
    composition.hidesBottomBarWhenPushed = YES;
    composition.model = model;
    [self.navigationController pushViewController:composition animated:YES];
    
}









#pragma mark - CustomDelegate
- (void)carouselView:(XRCarouselView *)carouselView didClickImage:(NSInteger)index {
//    NSLog(@"点击了第%ld张图片", index);
    //判断网络
    if (self.imgCaroselArrays.count == 0) {
        [self showAlertWithTitle:@"温馨提示" message:@"你的网络有问题哦!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    //进入web
    XHF_WebViewController *web = [XHF_WebViewController new];
    
    NSMutableArray *array = [NSMutableArray array];
    for (CaroselModel *model in self.imgCaroselArrays) {
        [array addObject:model.link_url];
    }
    
    web.url = array[index];
    web.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:web animated:YES];
    
}

#pragma mark - NetworkToolerDelegate
- (void)returnData:(id)data{
    
    [self endRefresh];
    self.bgView.hidden = YES;

    
    if (isNSDictionary) {
        
        //列表
        if (_requstType == 1) {
            [GiabHUD hideUIBlockingIndicator];
            self.view.hidden = NO;

            
            if (_loadpage == 1) {
                [self.workerListArray removeAllObjects];
            }
            NSArray *array = [data objectForKey:@"data"];
            _total =[[data objectForKey:@"total"] integerValue];
            
            for (NSMutableDictionary *dic in array) {
                HomeListModel *model = [HomeListModel modelWithDictionary:dic];
                
                [self.workerListArray addObject:model];
            }
            
            
            [self.homeTableView reloadData];
        }
        //轮播
        
        if (_requstType == 2) {
            [self _postWorkerListDataWithPage:_loadpage];
            
            
            [self.imgCaroselArrays removeAllObjects];
            NSMutableArray *saveArr = [NSMutableArray array];
            
            NSArray *arr = data[@"data"];
            for (NSMutableDictionary *dic in arr) {
                CaroselModel *model = [CaroselModel modelWithDictionary:dic];
                [self.imgCaroselArrays addObject:model];
                [saveArr addObject:[model.pic_url stringByAppendingString:caroselmain]];
            }
            
            //写入本地
//            [self _arrayWriteTofile:saveArr];
            
            
            [self.homeTableView reloadData];
        }
        
        
        
        
        
        
        
    }
}

- (void)returnRequestError:(NSError *)error{
    [GiabHUD hideUIBlockingIndicator];

    [self endRefresh];
    
}

- (void)returnMsg:(NSString *)Msg{
    
    if ([Msg isEqualToString:@"你的网络有问题哦!"]) {
        [GiabHUD hideUIBlockingIndicator];
        self.view.hidden = NO;
        self.bgView.hidden = NO;
        [self.workerListArray removeAllObjects];
        [self.imgCaroselArrays removeAllObjects];
        [_homeTableView reloadData];

    }
    
    [self endRefresh];
    
    [self showAlertWithTitle:@"温馨提示" message:Msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
    
    
}
#pragma mark - private methods
- (void)_arrayWriteTofile:(NSArray *)array{
    
    NSString *path = [DOCUMENT stringByAppendingPathComponent:@"caroselArray.plist"];
    
    
    BOOL result = [array writeToFile:path atomically:YES];
    
    if (result) {
        NSLog(@"caroselArray写入成功%@", path);
    } else {
        NSLog(@"caroselArray写入失败");
    }
    
}

-(void)updateNewData{
    
    _loadpage = 1;
    [self _postCaroselData];
    
    
}

-(void)updateMoreData{
    
    _loadpage++;
    
    if (_loadpage <= (int)((_total/listConut)+1)) {
        
        [self _postCaroselData];
    }else{
        
        [_homeTableView.mj_footer endRefreshingWithNoMoreData];
        
    }
    
    
    
}
-(void)endRefresh{
    [_homeTableView.mj_header endRefreshing];
    [_homeTableView.mj_footer endRefreshing];
}

#pragma mark - gettsers and setters






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
